package br.edu.univas.jobmanager.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.swing.JFileChooser;

import org.apache.commons.io.FileUtils;

/**
 * @author daniel
 *	Baseado em pesquisas:
 * Fonte: http://www.webartigos.com/articles/28886/1/ZipUnzip-em-Java/pagina1.html#ixzz1QWV1n1y5
 */
public class BackupDAO {

	public void recuperaBackup() throws IOException {
		
		//Renomeando os arquivos na pasta database.
		FileUtils.copyFile(new File("database/jobmanager.data"), new File("database/jobmanager.data.old"));
		FileUtils.copyFile(new File("database/jobmanager.script"), new File("database/jobmanager.script.old"));
		FileUtils.copyFile(new File("database/jobmanager.properties"), new File("database/jobmanager.properties.old"));
		
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(null);

		ZipFile zip = new ZipFile(chooser.getSelectedFile().getAbsolutePath());
		String dir = "database";
		File arquivo = null;
		InputStream is = null;
		OutputStream os = null;
		byte[] buffer = new byte[1024];

		try {
			@SuppressWarnings("rawtypes")
			Enumeration e = zip.entries();
			while (e.hasMoreElements()) {
				ZipEntry entrada = (ZipEntry) e.nextElement();
				arquivo = new File(dir, entrada.getName());

				if (entrada.isDirectory() && !arquivo.exists()) {
					arquivo.mkdirs();
					continue;
				}

				// se a estrutura de diretórios não existe, cria
				if (!arquivo.getParentFile().exists()) {
					arquivo.getParentFile().mkdirs();
				}
				try {
					// lê o arquivo do zip e grava em disco
					is = zip.getInputStream(entrada);
					os = new FileOutputStream(arquivo);
					int bytesLidos = 0;
					if (is == null) {
						throw new ZipException("Erro ao ler a entrada do zip: "
								+ entrada.getName());
					}
					while ((bytesLidos = is.read(buffer)) > 0) {
						os.write(buffer, 0, bytesLidos);
					}
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (Exception ex) {
						}
					}
					if (os != null) {
						try {
							os.close();
						} catch (Exception ex) {
						}
					}
				}
			}
		} finally {
			if (zip != null) {
				try {
					zip.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public void geraBackup() throws IOException {
		String backupDataPath = "database/jobmanager.data";
		String backupScriptPath = "database/jobmanager.script";
		String backupPropertiesPath = "database/jobmanager.properties";
		File dataFile = new File(backupDataPath);
		File scriptFile = new File(backupScriptPath);
		File propertiesFile = new File(backupPropertiesPath);

		byte[] buffer = new byte[1024];
		int length;

		JFileChooser chooser = new JFileChooser();
		chooser.setSelectedFile(dataFile);
		chooser.showSaveDialog(null);

		ZipOutputStream zipBackup = new ZipOutputStream(new FileOutputStream(
				chooser.getSelectedFile().getAbsoluteFile().getAbsolutePath()
						+ ".zip"));

		FileInputStream dataFileInputStream = new FileInputStream(dataFile);
		FileInputStream scriptFileInputStream = new FileInputStream(scriptFile);
		FileInputStream propertiesFileInputStream = new FileInputStream(
				propertiesFile);

		ZipEntry dataEntry = new ZipEntry(dataFile.getName());
		zipBackup.putNextEntry(dataEntry);

		while ((length = dataFileInputStream.read(buffer)) > 0) {
			zipBackup.write(buffer, 0, length);
		}

		zipBackup.closeEntry();

		ZipEntry scriptEntry = new ZipEntry(scriptFile.getName());
		zipBackup.putNextEntry(scriptEntry);

		while ((length = scriptFileInputStream.read(buffer)) > 0) {
			zipBackup.write(buffer, 0, length);
		}

		zipBackup.closeEntry();

		ZipEntry propertiesEntry = new ZipEntry(propertiesFile.getName());
		zipBackup.putNextEntry(propertiesEntry);

		while ((length = propertiesFileInputStream.read(buffer)) > 0) {
			zipBackup.write(buffer, 0, length);
		}

		zipBackup.closeEntry();

		zipBackup.close();

	}

}
